<template>
  <div class="appScreen">
    <div ref="map" class="map"></div>
    <div class="mapButtonContainer">
      <button
        class="mapButton"
        id="btnAddPoints"
        @click="displayPointJSONData()"
      >
        撒点
      </button>
      <button
        class="mapButton"
        id="btnAddXhPoints"
        @click="displayXhPointJSONData()"
      >
        撒点（标序号）
      </button>
      <button
        class="mapButton"
        id="btnAddPoints"
        @click="displayPolygonJSONData()"
      >
        画面
      </button>

      <button
        class="mapButton"
        id="btnOpenDefaultPopuup"
        @click="togglePopupTemplate(true)"
      >
        开启默认弹窗
      </button>

      <button class="mapButton" id="btnPopupIframe" @click="openPopupIframe()">
        弹窗（ifame）
      </button>

      <button class="mapButton" id="btnPopupHtml" @click="openPopupHtml()">
        弹窗（html）
      </button>
    </div>
  </div>
</template>
<style>
.appScreen {
  height: 100%;
  width: 100%;
}

.map {
  height: 100%;
  width: 100%;
}

.esri-compass {
  position: absolute;
  top: 175px !important;
}

.mapButtonContainer {
  width: 20%;
  display: flex;
  flex-flow: row;
  position: absolute;
  top: 5px;
  right: 10px;
  display: block;
}

.mapButtonContainer .mapButton {
  width: 100px;
  height: 40px;
  margin-right: 15px;
  margin-bottom: 15px;
  float: left;
}
</style>

<script>
import mapconfig from '@/config/config_map.js'

import jsapiUtil from '@/utils/jsapi'
import * as esriloader from 'esri-loader'

import testParams from '@/config/testData.js'
import clientLayersOperate from '@/utils/clientLayersOperate.js'
import senceViewPopup from '@/utils/senceViewPopup.js'

export default {
  name: 'MyMap',
  props: {
    msg: String,
  },
  async mounted() {
    esriloader.loadCss(mapconfig.cssUrl) //添加样式
    var that = this

    const [
      esriConfig,
      Map,
      Basemap,
      SceneView,
      MapView,
      SpatialReference,
      IdentityManager,
      Camera,
      LayerList,
      Expand,
      Fullscreen,
      Legend,
      GroupLayer,
      TileLayer,
      SceneLayer,
      FeatureLayer,
      DirectLineMeasurement3D,
      AreaMeasurement3D,
      Graphic,
      watchUtils,
      urlUtils,
    ] = await jsapiUtil.load([
      'esri/config',
      'esri/Map',
      'esri/Basemap',
      'esri/views/SceneView',
      'esri/views/MapView',
      'esri/geometry/SpatialReference',
      'esri/identity/IdentityManager',
      'esri/Camera',
      'esri/widgets/LayerList',
      'esri/widgets/Expand',
      'esri/widgets/Fullscreen',
      'esri/widgets/Legend',
      'esri/layers/GroupLayer',
      'esri/layers/TileLayer',
      'esri/layers/SceneLayer',
      'esri/layers/FeatureLayer',
      'esri/widgets/DirectLineMeasurement3D',
      'esri/widgets/AreaMeasurement3D',
      'esri/Graphic',
      'esri/core/watchUtils',
      'esri/core/urlUtils',
    ])

    esriConfig.request.useIdentity = false


    //增加历史影像节点
    urlUtils.addProxyRule({
      urlPrefix: 'http://smiserver.gtj.sh.cegn.cn',
      proxyUrl: 'http://10.108.3.41/DotNet2/proxy.ashx',
    })
    const air2021Layer = await new TileLayer(
      'http://smiserver.gtj.sh.cegn.cn/OneMapServer/rest/services/sat_gj1_2020q4_3857/MapServer',
      {
        id: 'air2021Basemap',
        visible: true,
        opacity: 1,
        title: '2021年航空影像',
      }
    )



    const air2020Layer = await new TileLayer(
      'http://10.89.5.14/arcgis/rest/services/airmap/air2020_kp_3857/MapServer',
      {
        id: 'air2020Basemap',
        visible: true,
        opacity: 1,
        title: '2020年航空影像',
      }
    )

    const air2019Layer = await new TileLayer(
      'http://smiserver.gtj.sh.cegn.cn/OneMapServer/rest/services/air_2019_3857/MapServer',
      {
        id: 'air2019Basemap',
        visible: true,
        opacity: 1,
        title: '2019年航空影像',
      }
    )

    const air2018Layer = await new TileLayer(
      'http://smiserver.gtj.sh.cegn.cn/OneMapServer/rest/services/air_2018_3857/MapServer',
      {
        id: 'air2018Basemap',
        visible: true,
        opacity: 1,
        title: '2018年航空影像',
      }
    )

    const air2017Layer = await new TileLayer(
      'http://smiserver.gtj.sh.cegn.cn/OneMapServer/rest/services/air_2017_3857/MapServer',
      {
        id: 'air2017Basemap',
        visible: true,
        opacity: 1,
        title: '2017年航空影像',
      }
    )

    const baseLayer = await new TileLayer(
      'http://10.89.5.14/arcgis/rest/services/basemap/base_kp_3857/MapServer',
      {
        id: 'zhengwuBasemap',
        visible: true,
        opacity: 1,
        title: '政务底图',
      }
    )

    const darkblackLayer = await new TileLayer(
      'http://10.89.5.14/arcgis/rest/services/basemap/darkblack_kp_3857/MapServer',
      {
        id: 'air2020',
        visible: true,
        opacity: 1,
        title: '暗黑底图',
      }
    )
    window.map = new Map({
      ground: {
        surfaceColor: '#021425',
      },
    })

    const initCamera = {
      heading: 0,
      tilt: 0.49999999999913347,
      fov: 55,
      position: {
        x: 31677.802827289288,
        y: -33415.02681828593,
        z: 95587.70223144352,
        spatialReference: SpatialReference.WebMercator,
      },
    }

    window.sceneView = new SceneView({
      container: this.$refs.map,
      viewingMode: 'local',
      map: map,
      camera: initCamera,
      popup: {
        defaultPopupTemplateEnabled: true,
      },
    })

    var fullScreen = new Fullscreen({
      view: window.sceneView,
    })

    var layerList = new LayerList({
      view: window.sceneView,
    })

    var layerListExpand = new Expand({
      expandTooltip: '图层控制',
      view: window.sceneView,
      content: layerList,
    })

    var directLineMeasurement3DExpand = new Expand({
      expandIconClass: 'esri-icon-minus',
      view: window.sceneView,
      expandTooltip: '测距',
    })

    var areaMeasurement3DExpand = new Expand({
      expandIconClass: 'esri-icon-polygon',
      view: window.sceneView,
      expandTooltip: '测面积',
    })

    var directLineMeasurement3D, areaMeasurement3D
    directLineMeasurement3DExpand.watch('expanded', function(expanded) {
      if (expanded) {
        layerListExpand.collapse()
        areaMeasurement3DExpand.collapse()
        directLineMeasurement3D = new DirectLineMeasurement3D({
          view: window.sceneView,
        })
        directLineMeasurement3D.viewModel.newMeasurement()
        directLineMeasurement3DExpand.content = directLineMeasurement3D
      } else {
        directLineMeasurement3D.viewModel.clearMeasurement()
      }
    })

    areaMeasurement3DExpand.watch('expanded', function(expanded) {
      if (expanded) {
        layerListExpand.collapse()
        directLineMeasurement3DExpand.collapse()
        areaMeasurement3D = new AreaMeasurement3D({
          view: window.sceneView,
        })
        areaMeasurement3D.viewModel.newMeasurement()
        areaMeasurement3DExpand.content = areaMeasurement3D
      } else {
        areaMeasurement3D.viewModel.clearMeasurement()
      }
    })

    var legend = new Legend({
      view: window.sceneView,
    })

    var legendExpand = new Expand({
      expandTooltip: '显示图例',
      expanded: false,
      view: window.sceneView,
      content: legend,
    })

    window.sceneView.ui.add(legendExpand, 'bottom-left')
    window.sceneView.ui.add(
      [
        layerListExpand,
        directLineMeasurement3DExpand,
        areaMeasurement3DExpand,
        fullScreen,
      ],
      'top-left'
    )
    window.sceneView.ui.remove([
      'zoom',
      'navigation-toggle',
      'attribution',
      // 'compass',
    ])

    const baseMapGroupLayer = new GroupLayer({
      title: '基础底图',
      visible: true,
      visibilityMode: 'exclusive',
      layers: [
        air2021Layer,
        air2020Layer,
        air2019Layer,
        air2018Layer,
        air2017Layer,
        baseLayer,
        darkblackLayer,
      ],
      opacity: 1,
    })
    map.layers.add(baseMapGroupLayer)

    var cityBuildingLayer = new SceneLayer({
      url:
        'http://10.89.5.14/arcgis/rest/services/Hosted/WhiteModel/SceneServer',
      title: '全市白模',
      visible: false,
      elevationInfo: {
        mode: 'absolute-height',
        offset: 0.05,
      },
      renderer: {
        authoringInfo: {
          visualVariables: [
            {
              field: 'BUILDING_HEIGHT',
              maxSliderValue: 200,
              minSliderValue: 1,
              theme: 'high-to-low',
              type: 'color',
            },
          ],
        },
        type: 'class-breaks',
        visualVariables: [
          {
            type: 'color',
            field: 'BUILDING_HEIGHT',
            stops: [
              {
                value: '',
                color: [20, 96, 166, 0.7],
                label: '暂缺',
              },
              {
                value: 1,
                color: [20, 96, 166, 0.7],
                label: '< 1',
              },
              {
                value: 40,
                color: [55, 135, 192, 0.7],
              },
              {
                value: 80,
                color: [148, 195, 223, 0.7],
                label: '80',
              },
              {
                value: 120,
                color: [230, 238, 251, 0.7],
              },
              {
                value: 160,
                color: [235, 240, 249, 0.7],
                label: '> 160',
              },
            ],
          },
        ],
        classBreakInfos: [
          {
            maxValue: 1.7976931348623157e308,
            symbol: {
              type: 'mesh-3d',
              symbolLayers: [
                {
                  material: {
                    color: [170, 170, 170],
                    colorMixMode: 'replace',
                  },
                  type: 'fill',
                  edges: {
                    type: 'solid',
                    color: [0, 0, 0],
                    transparency: 60,
                    size: 0.5,
                  },
                },
              ],
            },
            minValue: -1.7976931348623157e308,
          },
        ],
        field: 'BUILDING_HEIGHT',
      },
    })

    var lgBuildingLayer = new SceneLayer({
      url:
        'http://10.89.5.14/arcgis/rest/services/Hosted/lgBuilding/SceneServer',
      title: '临港白模',
      visible: false,
      elevationInfo: {
        mode: 'absolute-height',
        offset: 0.05,
      },
      renderer: {
        authoringInfo: {
          visualVariables: [
            {
              field: 'Height',
              maxSliderValue: 200,
              minSliderValue: 1,
              theme: 'high-to-low',
              type: 'color',
            },
          ],
        },
        type: 'class-breaks',
        visualVariables: [
          {
            type: 'color',
            field: 'Height',
            stops: [
              {
                value: '',
                color: [20, 96, 166, 0.7],
                label: '暂缺',
              },
              {
                value: 6,
                color: [20, 96, 166, 0.7],
                label: '< 1',
              },
              {
                value: 12,
                color: [55, 135, 192, 0.7],
              },
              {
                value: 18,
                color: [148, 195, 223, 0.7],
                label: '8',
              },
              {
                value: 24,
                color: [230, 238, 251, 0.7],
              },
              {
                value: 30,
                color: [235, 240, 249, 0.7],
                label: '> 30',
              },
            ],
          },
        ],
        classBreakInfos: [
          {
            maxValue: 1.7976931348623157e308,
            symbol: {
              type: 'mesh-3d',
              symbolLayers: [
                {
                  material: {
                    color: [170, 170, 170],
                    colorMixMode: 'replace',
                  },
                  type: 'fill',
                  edges: {
                    type: 'solid',
                    color: [0, 0, 0],
                    transparency: 60,
                    size: 0.5,
                  },
                },
              ],
            },
            minValue: -1.7976931348623157e308,
          },
        ],
        field: 'Height',
      },
    })

    const modelGroupLayer = new GroupLayer({
      title: '建筑模型',
      visible: true,
      visibilityMode: 'independent',
      layers: [cityBuildingLayer, lgBuildingLayer],
      opacity: 1,
    })
    map.layers.add(modelGroupLayer)

    //业务图层(静态)

    const xinpianquRegion = new FeatureLayer({
      title: '新片区边界',
      url: 'http://10.89.5.14/arcgis/rest/services/region/lg_region/MapServer',
      group: 'LGlabel',
      renderer: {
        type: 'simple',
        symbol: {
          type: 'simple-fill',
          color: [255, 235, 175, 0.1],
          outline: {
            color: [255, 235, 175, 1],
            width: '1.5px',
          },
        },
      },
      labelingInfo: [
        {
          symbol: {
            type: 'label-3d',
            symbolLayers: [
              {
                type: 'text',
                material: {
                  color: [255, 255, 190, 1],
                },
                halo: {
                  color: [0, 0, 0, 0.7],
                  size: 4,
                },
                size: 20,
                font: { weight: 'bold' },
              },
            ],
          },
          // labelPlacement: "above-center",
          // labelExpressionInfo: {
          //   expression: "$feature.name",
          // },
        },
      ],
      elevationInfo: {
        mode: 'absolute-height',
        offset: 8,
      },
      definitionExpression: "NAME='360' ",
      // definitionExpression:"NAME='360' OR NAME='873'"
    })

    const regionGroupLayer = new GroupLayer({
      title: '边界图层',
      visible: true,
      visibilityMode: 'independent',
      layers: [xinpianquRegion],
      opacity: 1,
    })
    map.layers.add(regionGroupLayer)

    const guihuaModel = new FeatureLayer({
      title: '公共交通设施',
      url:
        'http://10.108.3.50/changsanjiao/rest/services/Lgplaninfo/FeatureServer/1',
      group: 'landplan873',
      elevationInfo: {
        mode: 'absolute-height',
        offset: 8,
      },
    })

    const guihualandModel = new FeatureLayer({
      title: '公共交通线位',
      url:
        'http://10.108.3.50/changsanjiao/rest/services/Lgplaninfo/FeatureServer/2',
      group: 'landplan873',
      elevationInfo: {
        mode: 'absolute-height',
        offset: 8,
      },
    })
    const guihuayongdiModel = new FeatureLayer({
      title: '规划用地',
      url:
        'http://10.108.3.50/changsanjiao/rest/services/LG_landuse1/FeatureServer/0',
      group: 'landplan873',
      elevationInfo: {
        mode: 'absolute-height',
        offset: 8,
      },
    })

    const guihuaGroupLayer = new GroupLayer({
      title: '规划图层',
      visible: false,
      visibilityMode: 'independent',
      layers: [guihuaModel, guihualandModel, guihuayongdiModel],
      opacity: 1,
    })
    map.layers.add(guihuaGroupLayer)

    window.sceneView.on('click', function(event) {
      sceneView.hitTest(event).then(async function(response) {
        if (response.results.length > 0) {
          const layername = response.results[0].graphic.layer.id
          let objectid = null
          objectid = response.results[0].graphic.attributes.objectid
          console.log(layername)
          switch (layername) {
            //可根据图层名称对应不同操作

            default:
              const graphiclayer = window.map.findLayerById(
                response.results[0].graphic.layer.id
              )
              if (graphiclayer != null && graphiclayer != undefined) {
                const graphiclist = graphiclayer.source.items.find(function(
                  result
                ) {
                  return (
                    result.attributes.OBJECTID ===
                    response.results[0].graphic.attributes.OBJECTID
                  )
                })
                if (graphiclist != undefined) {
                  window.sceneView.goTo([response.results[0].graphic])
                  const params = {
                    location: {
                      codX: response.results[0].graphic.geometry.x,
                      codY: response.results[0].graphic.geometry.y,
                      codZ: 0,
                    },
                    title: graphiclist.attributes.OBJECTID,
                    content: {
                      type: 'url',
                      url: 'http://www.baidu.com',
                    },
                  }
                  console.log(graphiclist.attributes)
                  that.togglePopupTemplate(false)
                  that.setPopupContent(params)
                }
              }
          }
        }
      })
    })
  },
  methods: {
    async displayPointJSONData() {
      await clientLayersOperate.displayJSONData(
        JSON.parse(testParams.pointsParameters)
      )
    },
    async displayXhPointJSONData() {
      await clientLayersOperate.displayJSONData(
        JSON.parse(testParams.pointsXhParameters)
      )
    },
    async displayPolygonJSONData() {
      await clientLayersOperate.displayJSONData(
        JSON.parse(testParams.polygonParameters)
      )
    },
    //打开 关闭弹窗
    togglePopupTemplate(trueOrFalse) {
      if (trueOrFalse === true) {
        window.sceneView.popup.autoOpenEnabled = true
      } else {
        window.sceneView.popup.autoOpenEnabled = false
      }
    },
    // 设置 弹窗内容
    async setPopupContent(Parameters) {
      const [Point, SpatialReference] = await jsapiUtil.load([
        'esri/geometry/Point',
        'esri/geometry/SpatialReference',
      ])

      const dockpoint = new Point({
        x: Parameters.location.codX,
        y: Parameters.location.codY,
        z: Parameters.location.codZ,
        spatialReference: SpatialReference.WebMercator,
      })
      window.sceneView.popup.open({
        actions: [],
        location: dockpoint,
        title: Parameters.title,
        collapseEnabled: false,
        dockEnabled: false,
        content: senceViewPopup.createCustompopup(Parameters.content),
      })
    },
    openPopupIframe() {
      this.togglePopupTemplate(false)
      this.setPopupContent(JSON.parse(testParams.popupIframeParameters))
    },
    openPopupHtml() {
      this.togglePopupTemplate(false)
      this.setPopupContent(JSON.parse(testParams.popupHtmlParameters))
    },
  },
}
</script>
